<template>
  <!-- 现场发料编辑 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="发料明细"
          name="receivingMaterials"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
                <BillTop title="现场发料编辑" @cancel="cancel"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                  <el-form
                    :model="basicFormData"
                    label-width="150px"
                    ref="ruleForm"
                    :rules="rules"
                    class="demo-ruleForm"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="业务类型：" prop="businessType">
                          <el-select
                            v-model="basicFormData.businessType"
                            placeholder="请选择"
                             @change="businessTypeChange"
                          >
                            <el-option
                              v-for="item in options"
                              :key="item.value"
                              :label="item.key"
                              :value="item.value"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="合同：">
                          <el-input
                            v-model="basicFormData.sourceNumber"
                            :disabled="isDisabled"
                            @input="sourceNumberChange()"
                          >
                            <i
                              slot="suffix"
                              class="el-input__icon el-icon-document-copy"
                              @click="selectContract()"
                              v-if="basicFormData.businessType === 1 ||basicFormData.businessType === 2 || basicFormData.businessType === 3"
                            ></i>
                          </el-input>
                          <el-button
                            type="primary"
                            style="background: #2e61d7; margin-left: 5px"
                             v-if="basicFormData.businessType === 1 ||basicFormData.businessType === 2 || basicFormData.businessType === 3"
                             @click="Examine"
                            >查看</el-button
                          >
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="领料单位：">
                          <el-input
                            v-model="basicFormData.pickingUnitName"
                            :disabled="isDisabled"
                          >
                            <i
                              slot="suffix"
                              class="el-input__icon el-icon-document-copy"
                              @click="selectPickingUnitName"
                              v-if="basicFormData.businessType === 4 || basicFormData.businessType === 5"
                            ></i>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="领料人员：" prop="pickingPersonnelName">
                          <el-input
                            v-model="basicFormData.pickingPersonnelName"
                            :disabled="isDisabled"
                          >
                            <i
                              slot="suffix"
                              class="el-input__icon el-icon-document-copy"
                              @click="SelectMaterialReturnPersonnelName"
                            ></i>
                          </el-input>
                          <el-button
                          v-if="basicFormData.businessType != 4 "
                            type="primary"
                            style="background: #2e61d7; margin-left: 5px"
                            @click="AddPersonnelName"
                            >添加乙方人员</el-button
                          >
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="发料编号：">
                          {{ basicFormData.billNo }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="发料日期：" prop="issueDate">
                          <el-date-picker
                            v-model="basicFormData.issueDate"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                            :clearable="false"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="发料人员：">
                          {{ basicFormData.issuingPersonnelName }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="所属机构：">
                          {{ basicFormData.orgName }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="发料数量：">
                          {{ basicFormData.issuedQuantity }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="状态：">
                          {{
                            ["草稿", "审核中", "已审核", "已关闭",'', "已作废"][
                              basicFormData.state
                            ]
                          }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-form-item label="备注：">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>

                  </el-form>
                </div>
              </div>
            </div>
          </div>

          <!-- 发料明细 -->
          <div id="receivingMaterialsCon" class="con">
            <div class="tabs-title" id="receivingMaterials">发料明细</div>
            <div class="e-table">
              <div class="top">
                <div class="left">
                  <div>
                    <el-button
                      size="small"
                      style="background: rgb(75, 178, 255); color: #fff"
                      class="btn-blue"
                      @click="selectMaterial()"
                      >选择库存</el-button
                    >
                  </div>
                </div>
              </div>
              <div class="errorMsg" v-if="errorMsg.length>0">
                    <span v-for="item,index in errorMsg" :key="index">
                        {{item}}
                    </span>
                </div>
              <el-table
                :data="receivingList"
                border
                style="width: 100%"
                :row-class-name="tableRowClassName"
                :cell-class-name="cellClsNm"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }"
                row-key="uuid"
                :max-height="$store.state.tableHeight"
                ref="table"
                v-sortTable="{ 'tableData': receivingList, '_this': this, 'ref': 'table' }"
              >
                <el-table-column
                  label="操作"
                  fixed
                  width="100px"
                  align="left"
                  v-if="isBatch"
                >
                  <template slot-scope="{ row, $index }">
                    <i
                      class="el-icon-delete"
                      style="cursor: pointer; font-size: 20px; color: red"

                      @click="deleteEle(row)"
                      v-if="$index > 0&& row.billId"
                    ></i>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="materialClassName"
                  label="物资类别"
                  min-width="150"
                >
                </el-table-column>
                <el-table-column
                  prop="materialName"
                  label="物资名称"
                  min-width="150"
                >
                </el-table-column>
                <el-table-column prop="spec" label="规格" min-width="100">
                </el-table-column>
                <el-table-column prop="texture" label="材质" min-width="100">
                </el-table-column>
                <el-table-column prop="unit" label="单位" min-width="150">
                </el-table-column>
                <el-table-column
                  prop="projectDepartmentWarehouseName"
                  label="项目部仓库"
                  min-width="150"
                >
                </el-table-column>
                <el-table-column
                  prop="inventoryQuantity"
                  label="库存数量"
                  min-width="100"
                >
                </el-table-column>
                <el-table-column
                  prop="receivingUnitWarehouseName"
                  min-width="150"
                >
                 <template  slot="header">
                    <span>领料单位仓库</span>
                    <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectWarehouse"></i>
                  </template>
                  <!-- <template slot-scope="{ row }"> -->
                  <!-- <el-input
                    @input="input(row)"
                    v-model="row.purchasingUnitName"
                      v-if="$index > 0"
                  > -->
                  <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;"></i>
                  <!-- </el-input> -->
                <!-- </template> -->
                </el-table-column>
                <el-table-column
                  prop="subItemName"
                  min-width="100"
                  v-if="basicFormData.businessType === 1"
                >
                    <template  slot="header">
                    <span>分部分项</span>
                    <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectsubItemName"></i>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="partyAQuantity"
                  label="甲供数量"
                  min-width="100"
                >
                </el-table-column>
                <el-table-column
                  prop="receivingQuantity"
                  label="领用数量"
                  min-width="100"
                >
                  <template slot-scope="{ row, $index }">
                    <el-input
                     v-enter-float2="{
                          set: row,
                          key: 'receivingQuantity'
                      }"
                      @input="input(row)"
                      v-model="row.receivingQuantity"
                      clearable
                      v-if="$index > 0&& row.billId"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="partyAType" label="甲供类型" min-width="100">
                     <template slot-scope="{ row,$index  }">
                      <el-select v-model="row.partyAType" placeholder="请选择" v-if="$index > 0&& row.billId" @change="selectPartyAType(row)">
                          <el-option
                            v-for="item in procurementMethod"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                    </el-select>
                    </template>
                </el-table-column>
                <el-table-column
                  prop="inventoryRemainingQuantity"
                  label="库存剩余"
                  min-width="100"
                >
                </el-table-column>

              </el-table>
            </div>
          </div>

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="material"
              v-if="objFlag.flag5"
            />
            <div class="seize-a-seat" v-else>
              <i class="el-icon-loading"></i>
            </div>
          </div>
          <!-- 审核历史 -->
          <div id="auditHistoryCon" class="con">
            <div class="tabs-title" id="auditHistory">审核历史</div>
            <div class="e-table">
              <ComAuditHistoryIndex
                :tableData.sync="auditHistoryTable"
                @getAuditHistory="getAuditHistory"
                ref="AuditHistoryRef"
              />
            </div>
          </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
       <el-button
          type="primary"
          style="background: #2e61d7"
          v-debounce
          v-if="basicFormData.state === '1'"
          >打印</el-button
      >
         <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />

             <!-- <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="nullify()"
        >作废</el-button
          > -->
      <!-- <el-button
        type="primary"
        style="background: #2e61d7"
        @click="save('basicFormData')"
        v-if="basicFormData.state === '0'"
        v-debounce
        >保存</el-button
      >
      <el-button
        type="primary"
        style="background: #2e61d7"
        @click="submit('basicFormData')"
        v-if="basicFormData.state === '0'"
        v-debounce
        >保存并提交</el-button
      >
       <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="state === '1'"
        @click="nullify()"
        >作废</el-button
          > -->
      <!-- <el-button type="danger" size="small" @click="ctDelete" v-if="basicFormData.state === '0'">删除</el-button> -->
      <el-button @click="cancel()">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import requests from '@/api/materials/sceneStoreIssue.js'
import { getUuid, selectDataClient, openAppClient } from '@/utils/common'
import { mapMutations } from 'vuex'
import CommonApi from '@/api/materials/common.js'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            auditState: {}, //按钮状态
            isBatch: true,
            isDisabled: false,
            tableData: [],
            auditHistoryTable: [], //审核历史
            receivingList: [], //发料明细
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                billId: '',
                billNo: '',
                businessType: null,
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                issueDate: '',
                issuedQuantity: 0,
                issuingPersonnelId: '',
                issuingPersonnelName: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                pickingPersonnelId: '',
                pickingPersonnelName: '',
                pickingUnitId: '',
                pickingUnitName: '',
                remarks: '',
                sourceId: '',
                sourceNumber: '',
                sourceName: '',
                state: '',
                workId: '',
            },
            procurementMethod: [{
                value: 1,
                label: '工程消耗'
            }, {
                value: 2,
                label: '研发支出'
            }, {
                value: 3,
                label: '安全环保支出'
            }],
            options: [
                {
                    value: 1,
                    key: '分包合同',
                },
                {
                    value: 2,
                    key: '加工合同',
                },
                {
                    value: 3,
                    key: '销售合同',
                },
                {
                    value: 4,
                    key: '事实合同',
                },
                {
                    value: 5,
                    key: '自行加工',
                },
            ],
            objFlag: {
                flag5: false,
            },
            //验证
            rules: {
                issueDate: [
                    { required: true, message: '请选择发料日期', trigger: 'change' },
                ],
                businessType: [
                    { required: true, message: '请选择业务类型', trigger: 'change' },
                ],
                pickingPersonnelName: [
                    { required: true, message: '请选择领料人员', trigger: 'change' },
                ],
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1009,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            auditParams: {
                billId: this.$route.query.billid, //单据Id  ***
                billType: '1009', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: this.orgId, //单据机构Id
                orgName: this.orgName, //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            },
            id: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            contractId: '',
            warehouseId: '',
            warehouseName: '',

        }
    },
    computed: {
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        'basicFormData.redBillState' () {
            if (this.basicFormData.redBillState == '3') {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.basicFormData.redBillState == '0' ||
                this.basicFormData.redBillState == '1'
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.basicFormData.redBillState == '2') {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.userId = localStorage.getItem('userId')
        this.userName = localStorage.getItem('userName')
        this.billid = this.$route.query.billid
        this.founderId = localStorage.getItem('userId')
        this.getBasicData() //进入页面就获取基本信息数据
        this.getAttach()
        this.getMasterPlan()
        this.getwarehouse()
        this.getCurrentUnitInfo()
        // setTimeout(()=>{
        //     this.totalIssuedQuantity()
        // }, 500)

    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'receivingMaterials', 'accessory', 'auditHistory']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        //选择结构部位
        selectsubItemName () {
            selectDataClient({
                SelectServiceToken: 'SelectProjectSettleDetail', //调动单和物资弹框
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: this.basicFormData.sourceId,
                Title: '引入清单' // 标题
            })
        },
        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1009,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.cancel, null, this.cancel)
                })
            })
        },
        //合同源单发生变化时清空数据
        sourceNumberChange () {
            this.basicFormData.pickingPersonnelId = ''
            this.basicFormData.pickingPersonnelName = ''
            this.receivingList = []

        },
        //业务类型发生改变清空数据
        businessTypeChange () {
            this.basicFormData.sourceId = ''
            this.basicFormData.sourceNumber =  ''
            this.basicFormData.pickingPersonnelId = ''
            this.basicFormData.pickingPersonnelName = ''
            this.basicFormData.pickingUnitId = ''
            this.basicFormData.pickingUnitName = ''
            this.basicFormData.issuedQuantity = 0
            this.receivingList = []

        },
        //汇总发料数量   汇总发料明细中领用数量累计。
        totalIssuedQuantity () {
            let num = 0
            this.receivingList.forEach(a=>{
                a.children.forEach(item=>{
                    num += Number(item.receivingQuantity)
                    this.basicFormData.issuedQuantity = num
                    this.basicFormData.issuedQuantity = this.basicFormData.issuedQuantity.toFixed(4)
                    item.inventoryRemainingQuantity = Number(item.inventoryQuantity) -  Number(item.receivingQuantity)  //库存剩余
                    item.inventoryRemainingQuantity = item.inventoryRemainingQuantity.toFixed(4)
                })
            })

        },
        // //计算库存剩余
        // totalinventoryRemainingQuantity () {
        //     this.receivingList.forEach(a=>{
        //         let
        //     })
        // },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //获取仓库  warehouseId: '', //仓库id warehouseName: '', //仓库名称
        getwarehouse () {
            this.$Ajax
                .httpGet({
                    url: '/material/warehouseManagement/getProjectDepartmentWarehouse',
                    params: {
                        orgId: this.orgId,
                    },
                })
                .then(res=>{
                    this.warehouseId = res.billId
                    this.warehouseName = res.name
                    console.log(' this.warehouseId', this.warehouseId)
                    console.log(' this.warehouseName', this.warehouseName)
                })
        },
        //选择甲供类型
        selectPartyAType (row) {
            console.log('row', row)
            this.receivingList.forEach(item=>{
                item.children.forEach(a=>{
                    if(row.dtlId === a.dtlId) {
                        // a.partyAType = row.partyAType
                        if(a.changeType === 1) {
                            a.changeType = 1
                        }else{
                            a.changeType = 2
                        }

                    }else if(a.changeType !== 2) {
                        a.changeType = 0
                    }
                })
            })
        },
        //选择领料单位仓库  //批量
        selectWarehouse () {
            let ids = []
            selectDataClient({
                SelectServiceToken:
          '/material/warehouseManagement/listBySubcontractorId', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    orgId: this.orgId,
                    subcontractorId: this.basicFormData.pickingUnitId,
                }),
                Title: '选择仓库', // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)

                    val.forEach(b=>{
                        this.receivingList.forEach(item=>{
                            item.children.forEach(a=>{
                                if(a.changeType === 1) {
                                    a.changeType = 1
                                }else{
                                    a.changeType = 2
                                }
                                a.receivingUnitWarehouseId = b.billId
                                a.receivingUnitWarehouseName = b.name
                            })
                        })
                    })

                })
        },
        // 查看
        Examine () {
            if(this.basicFormData.businessType === 1) {
                //查看分包合同
                let id = this.basicFormData.sourceId
                openAppClient(`/contractDefinitionShow?billid=${id}&isview=${true}`, '查看源单', function () {
                })
            }else  if(this.basicFormData.businessType === 2) {
                //查看加工合同
                let id = this.basicFormData.sourceId
                openAppClient(`/processingContractApplyShow?billid=${id}&isview=${true}`, '查看源单', function () {
                })
            } else  if(this.basicFormData.businessType === 3) {
                //查看物资销售合同
                let id = this.basicFormData.sourceId
                openAppClient(`/ctMaterialSalesSigningShow?billid=${id}&isview=${true}`, '查看源单', function () {
                })
            }

        },
        //选择合同
        selectContract () {
            if(this.basicFormData.businessType === 1) {
            //分包合同
                let businessType = 1
                this.selectContracts(businessType)
            }else if(this.basicFormData.businessType === 2) {
                //加工合同
                let businessType = 2
                this.selectContracts(businessType)
            }else if(this.basicFormData.businessType === 3) {
                //销售合同
                let businessType = 3
                this.selectContracts(businessType)
            }
        },
        selectContracts (businessType) {

            let ids = []
            selectDataClient({
                SelectServiceToken:
          '/subcontract/thirdParty/getSiteIssue', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({
                    contractType: businessType,
                }),
                Title: '选择合同', // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    this.sourceNumberChange()

                    val.forEach(item=>{

                        this.basicFormData.sourceId = item.contractId
                        this.basicFormData.sourceNumber = item.contractNumber
                        this.basicFormData.sourceName = item.contractName
                        this.basicFormData.pickingUnitId = item.secondPartyId
                        this.basicFormData.pickingUnitName = item.secondPartyName
                    })

                    // this.basicFormData.sourceId = val[0].contractId
                    // this.basicFormData.sourceNumber = val[0].contractName
                    // this.basicFormData.pickingUnitId = val[0].secondPartyId
                    // this.basicFormData.pickingUnitName = val[0].secondPartyName
                })
        },
        //获取基本信息数据
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/onSiteMaterialIssuance/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    this.basicFormData = res
                })
        },
        //获取明细数据
        getMasterPlan () {
            this.$Ajax
                .httpGet({
                    url: '/material/onSiteMaterialIssuance/getListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.receivingQuantity || 0),
                            0
                        )
                        item.materialName = `小计： ${count.toFixed(4)}`
                    })
                    this.receivingList = res
                })
        },
        //获取审核历史列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '1009',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: '',
            }
            CommonApi.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //选择领料人员()
        SelectMaterialReturnPersonnelName () {
            if(this.basicFormData.businessType !== 4) {
                let ids = []
                selectDataClient({
                    SelectServiceToken:
          '/material/personnelOfPartyB/listPersonnelInformationByFilter', // 客户端对应方法名
                    IsSingleMode: true, // 是否单选 true 单选 false 多选
                    SelectedIDs: ids, // 已选中id
                    InitParamsStr: JSON.stringify(this.basicFormData.pickingUnitId),
                    Title: '选择领料人', // 标题
                }).then(val => {
                    this.setSelectedInfo(val)

                    if(val.length == 0) {
                        this.clientPop('info', '未选到乙方人员或当前领料单位未维护乙方人员信息(请在基础管理-材料管理- 维护乙方人员!)')
                    }else{
                        val.forEach(item => {
                            this.basicFormData.pickingPersonnelName = item.name
                            this.basicFormData.pickingPersonnelId = item.dtlId
                        })
                    }
                })
            }else {
                let ids = []
                selectDataClient({
                    SelectServiceToken:
          '/outer/outer/get/factoOutSourcerClient', // 客户端对应方法名
                    IsSingleMode: true, // 是否单选 true 单选 false 多选
                    SelectedIDs: ids, // 已选中id
                    InitParamsStr: JSON.stringify({
                        'orgId': this.orgId, //机构id 非必填
                        'states': []//单据状态 非必填
                    }),
                    Title: '选择领料人', // 标题
                }).then(val => {
                // 保存用户选择返回数据到store
                    this.setSelectedInfo(val)
                    val.forEach(item => {
                        this.basicFormData.pickingPersonnelName = item.name
                        this.basicFormData.pickingPersonnelId = item.id
                    })
                })
            }
        },
        //添加乙方人员
        AddPersonnelName () {
            openAppClient('/materialPartBPerson', '添加乙方人员', function () {})
        },
        //选择领料单位
        selectPickingUnitName () {
            if(this.basicFormData.businessType === 4) {
                console.log('11', '事实合同选择事实合同外包方管理中的单位数据。')
                this.selectSub()

            }else if(this.basicFormData.businessType === 5) {
                console.log('22', '自行加工：选择往来单位中内部机构、其他')
                let ids = []
                selectDataClient({
                    SelectServiceToken: 'GeneralSelectOuter', // 客户端对应方法名
                    IsSingleMode: false, // 是否单选 true 单选 false 多选
                    SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                    InitParamsStr: JSON.stringify({
                        'businessTypes': [],
                        'businessUnitTypes': [],
                        'keyword': '',
                        'limit': 10,
                        'orgId': '',
                        'page': 1,
                        'states': [],
                        'subcontractorTypes': [],
                        'supplierTypes': [],
                        'type': [2]
                    },),    // 接口参数(name为模拟参数)
                    Title: '选择外包方' // 标题
                }).then(val=>{
                    this.setSelectedInfo(val)
                    val.forEach(item=>{
                        this.basicFormData.pickingUnitId = item.id
                        this.basicFormData.pickingUnitName = item.outerName
                    })
                })
            }
        },
        //
        selectSub () {
            let ids = []
            selectDataClient({
                SelectServiceToken: 'GeneralSelectOuter', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    'businessTypes': [],
                    'businessUnitTypes': [],
                    'keyword': '',
                    'limit': 10,
                    'orgId': '',
                    'page': 1,
                    'states': [],
                    'subcontractorTypes': [],
                    'supplierTypes': [],
                    'type': [3]
                },),
                Title: '选择外包方' // 标题
            }).then(val=>{
                this.setSelectedInfo(val)

                val.forEach(item=>{
                    this.basicFormData.pickingUnitId = item.id
                    this.basicFormData.pickingUnitName = item.outerName
                })
            })
        },
        //选择库存
        selectMaterial () {
            let ids = []
            let warehouseType = '0'
            selectDataClient({
                SelectServiceToken:
              '/material/stock/listUsableInventoryByOrgIdForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(warehouseType),
                Title: '选择库存明细', // 标题
            }).then(val => {
                this.setSelectedInfo(val)

                if(this.receivingList.length > 0) {
                    val.forEach(e=>{
                        this.receivingList.forEach(a=>{
                            const  Isrepeat =  a.children.some(b=>{
                                return b.materialName == e.materialName && b.spec == e.spec && b.texture == e.texture && b.changeType != -1
                            })
                            if(Isrepeat) {
                                this.clientPop('info', `物资明细不允许重复,物资类别:${e.materialClassName},物资名称:${e.materialName},规格:${e.spec},请检查!`)
                            }else{
                                e.materialClassNameArr = e.materialClassName.split('/')
                                e.materialClassIdArr = e.materialClassId.split('/')
                                e.materialClassNameArr.shift()
                                e.materialClassIdArr.shift()
                                const obj = {
                                    uuid: getUuid(),
                                    customId: getUuid(),
                                    billId: this.billid, //现场发料id
                                    changeType: 1, //
                                    conversionUnit: '', //转换单位
                                    dtlId: '', //现场发料明细id
                                    inventoryQuantity: e.quantity, //库存数量
                                    inventoryRemainingQuantity: e.quantity, //库存剩余
                                    materialClassId: e.materialClassIdArr.join('/'), //	物资类别id
                                    materialClassName: e.materialClassNameArr.join('/'), //	物资类别id
                                    materialId: e.materialId, //物资id
                                    materialName: e.materialName, //物资名称
                                    partyAQuantity: 0, //甲供数量
                                    partyAType: null, ////发料类型
                                    projectDepartmentWarehouseId: this.warehouseId, //项目部仓库id
                                    projectDepartmentWarehouseName: this.warehouseName, //项目部仓库id
                                    receivingQuantity: e.quantity, //领用数量
                                    receivingUnitWarehouseId: '', //领料单位仓库id
                                    receivingUnitWarehouseName: '', //领料单位仓库名称
                                    spec: e.spec, //规格型号
                                    subItemId: '', //分部分项id
                                    subItemName: '', //分部分项名称
                                    texture: e.texture, //材质
                                    unit: e.unit, //计量单位
                                }

                                this.receivingList.forEach(item=>{

                                    item.children.push(obj)
                                })
                            }
                        })
                        this.totalIssuedQuantity()

                    })
                }else {

                    const mapObj = {}
                    let arr = []
                    val.forEach(b => {
                        const children = []
                        // this.basicFormData.sourceId = b.billId
                        // this.basicFormData.sourceNumber = b.billNo
                        b.materialClassNameArr = b.materialClassName.split('/')
                        b.materialClassIdArr = b.materialClassId.split('/')
                        // TODO: 统计小计
                        let obj
                        const topClassId = b.materialClassIdArr.splice(0, 1).toString()
                        const topClassName = b.materialClassNameArr.splice(0, 1).toString()
                        if (!mapObj[topClassId]) {
                            obj = {
                                topClassId,
                                topClassName,
                                customId: topClassId,
                                materialClassId: topClassId,
                                materialClassName: topClassName,
                                uuid: getUuid(),
                                totalAmount: null,
                                totalQuantity: null,
                            }
                            //这里需要改成push多个对象   还没改
                            arr.push(obj)
                            mapObj[topClassId] = obj
                        } else {
                            obj = mapObj[topClassId]
                        }
                        // 物资名称
                        children.push({
                            uuid: getUuid(),
                            customId: getUuid(),
                            billId: this.billid, //现场发料id
                            changeType: 1, //
                            conversionUnit: '', //转换单位
                            dtlId: '', //现场发料明细id
                            inventoryQuantity: b.quantity, //库存数量
                            inventoryRemainingQuantity: b.quantity, //库存剩余
                            materialClassId: b.materialClassIdArr.join('/'), //	物资类别id
                            materialClassName: b.materialClassNameArr.join('/'), //	物资类别id
                            materialId: b.materialId, //物资id
                            materialName: b.materialName, //物资名称
                            partyAQuantity: 0, //甲供数量
                            partyAType: null, ////发料类型
                            projectDepartmentWarehouseId: this.warehouseId, //项目部仓库id
                            projectDepartmentWarehouseName: this.warehouseName, //项目部仓库id
                            receivingQuantity: b.quantity, //领用数量
                            receivingUnitWarehouseId: '', //领料单位仓库id
                            receivingUnitWarehouseName: '', //领料单位仓库名称
                            spec: b.spec, //规格型号
                            subItemId: '', //分部分项id
                            subItemName: '', //分部分项名称
                            texture: b.texture, //材质
                            unit: b.unit, //计量单位
                        })
                        obj.children = !obj.children
                            ? children
                            : obj.children.concat(children)
                        // 统计小计
                        const count = obj.children.reduce(
                            (prev, c) => (prev += c.receivingQuantity || 0),
                            0
                        )
                        obj.materialName = `小计： ${count.toFixed(4)}`
                        obj.children = this.uniqueArray(obj.children, 'customId')
                    })
                    this.receivingList = arr
                }
                this.totalIssuedQuantity()
            })
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        // //保存按钮
        // save (formName) {
        //     this.$refs[formName].validate(valid => {
        //         if (valid) {
        //             //基础信息
        //             const p1 = requests.EditsceneStoreIssue(this.basicFormData)
        //             //明细

        //             const p2 = requests.EditsceneStoreIssueList(this.receivingList)
        //             Promise.all([p1, p2]).then(() => {
        //                 this.clientPop('suc', '保存成功！', ()=>{
        //                     this.getBasicData(),
        //                     this.getMasterPlan()
        //                 })
        //             })
        //         } else {
        //             return false
        //         }
        //     })
        // },
        // //提交
        // submit (formName) {
        //     this.$refs[formName].validate(valid => {
        //         if (valid) {
        //             const params = {
        //                 billId: this.billid, //单据Id  ***
        //                 billType: '1009', //单据编码  ***
        //                 dtls: [], //审核中字段值变更历史
        //                 freeNextUnitIndex: 0, //下一步审核步骤
        //                 freeNextUser: '', //下一步审核人ID
        //                 isPass: true, //审核是否通过
        //                 isShareInAudit: true, //是否共享审核节点
        //                 opinion: '', //审核意见   ***
        //                 orgId: this.orgId, //单据机构Id
        //                 orgName: this.orgName, //单据机构名称
        //                 userId: this.userId, //审核人Id    ***
        //                 workId: '', //流程Id
        //             }
        //             const p1 = requests.EditsceneStoreIssue(this.basicFormData)
        //             const p2 = requests.EditsceneStoreIssueList(this.receivingList)
        //             const p3 = request.AuditCommit(params)
        //             Promise.all([p1, p2, p3]).then(() => {
        //                 this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
        //             })
        //         } else {
        //             return false
        //         }
        //     })
        // },
        //保存
        save () {
            let p1 =  requests.EditsceneStoreIssue(this.basicFormData)
            let p2 = requests.EditsceneStoreIssueList(this.receivingList)
            Promise.all([p1, p2]).then(() => {
                this.clientPop('suc', '保存成功', this.$router.go(0))
            })
            // this.errorList = []
            // Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
            //     .then(() => {
            //         this.clientPop('suc', '保存成功', this.$router.go(0))
            //     })
            //     .catch(() => {
            //         this.scorllError()
            //     })
        },

        // //保存并提交
        submit () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    CommonApi.AuditCommit(this.auditParams).then(() => {
                        this.clientPop('suc', '保存并提交成功', this.cancel, null, this.cancel)
                    })
                })
                .catch(() => {
                    this.scorllError()
                })

        },
        // //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        requests.EditsceneStoreIssue(this.basicFormData)
                            .then(() => {
                                this.getBasicData() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },

        // //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        requests.EditsceneStoreIssueList(this.receivingList)
                            .then(() => {
                                resolve()
                            })
                            .catch(err => {
                                this.setError('receivingMaterials')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('receivingMaterials')
                        reject(err)

                    })
            })
        },
        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if(this.receivingList.length === 0) {
                    let str = '发料明细不能为空！'
                    this.errorMsg.push(str)
                }
                else if (this.receivingList.length > 0) {
                    this.receivingList.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {
                                if (item.receivingQuantity === '' || item.receivingQuantity === null) {
                                    let str = `请填写第 ${index + 1} 行的领用数量`
                                    this.errorMsg.push(str)
                                }
                                if (item.partyAType === '' || item.partyAType === null) {
                                    let str = `请填写第 ${index + 1} 行的甲供类型`
                                    this.errorMsg.push(str)
                                }
                                if (item.receivingUnitWarehouseName === '' || item.receivingUnitWarehouseName === null) {
                                    let str = `请选择第 ${index + 1} 行的领料单位仓库`
                                    this.errorMsg.push(str)
                                }

                            }
                        })
                    })
                }
                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }

            })
        },
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //删除物资明细
        deleteEle (row) {
            row.changeType = -1
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //监听明细数据input事件
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else {
                row.changeType = 2
            }

            if(row.receivingQuantity > row.inventoryQuantity) {
                this.clientPop(
                    'err',
                    '领用数量不能超过库存数量!',
                )
                setTimeout(()=>{
                    row.receivingQuantity = row.inventoryQuantity
                    row.inventoryRemainingQuantity = 0
                })

            }

            let num = 0
            this.receivingList.forEach(a=>{
                a.children.forEach(item=>{
                    num += Number(item.receivingQuantity)
                })
            })
            this.basicFormData.issuedQuantity = num
            //计算库存剩余inventoryRemainingQuantity
            row.inventoryRemainingQuantity = Number(row.inventoryQuantity) - Number(row.receivingQuantity)
            row.inventoryRemainingQuantity = row.inventoryRemainingQuantity.toFixed(4)
        },
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/onSiteMaterialIssuance/delete',
                    params: {
                        id: this.billid,

                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel, null, this.cancel)
                    }
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./sceneStoreIssue')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
</style>